/**
 * Mock模式测试工具
 * 用于验证Mock模式下的连接和发送是否正常工作
 */

/**
 * 测试Mock模式WebSocket连接
 * @param {Object} config 组件实例或配置
 * @returns {Promise<boolean>} 测试结果
 */
export async function testMockWebSocketConnection(config = {}) {
    console.log('🧪 开始测试Mock模式WebSocket连接...');
    
    try {
        // 动态导入WebSocketManager
        const WebSocketManager = (await import('./WebSocketManager.js')).default;
        
        // 测试配置
        const testConfig = {
            mockMode: true,
            agentId: 'test-agent-001',
            historyId: 'test-history-001',
            logging: { enabled: true, level: 'debug' },
            reconnect: { enabled: false },
            heartbeat: { enabled: false },
            ...config
        };
        
        console.log('📋 测试配置:', testConfig);
        
        // 创建WebSocket管理器实例
        const wsManager = WebSocketManager.getInstance(testConfig);
        
        // 测试连接
        console.log('🔗 测试连接...');
        await wsManager.connect();
        
        const isConnected = wsManager.isConnected;
        console.log('📊 连接状态:', isConnected);
        
        if (!isConnected) {
            throw new Error('Mock模式连接失败');
        }
        
        // 测试消息发送
        console.log('📤 测试消息发送...');
        const testMessage = '这是一个测试消息';
        const sendOptions = {
            deepThink: true,
            webSearch: false
        };
        
        await wsManager.sendAIMessage(testMessage, sendOptions);
        console.log('✅ 消息发送成功');
        
        // 测试状态查询
        const status = wsManager.getState();
        console.log('📈 连接状态详情:', {
            isConnected: status.isConnected,
            mockMode: status.mockMode,
            agentId: status.agentId,
            connectionId: status.connectionId
        });
        
        // 清理资源
        wsManager.disconnect();
        
        console.log('✅ Mock模式WebSocket测试完成，所有功能正常');
        return true;
        
    } catch (error) {
        console.error('❌ Mock模式WebSocket测试失败:', error);
        return false;
    }
}

/**
 * 测试Mock模式深度思考功能
 */
export async function testMockDeepThink() {
    console.log('🧠 开始测试Mock模式深度思考功能...');
    
    try {
        const WebSocketManager = (await import('./WebSocketManager.js')).default;
        
        const wsManager = WebSocketManager.getInstance({
            mockMode: true,
            agentId: 'deep-think-test',
            historyId: 'deep-think-test-001',
            logging: { enabled: true, level: 'debug' }
        });
        
        // 设置深度思考消息监听
        let deepThinkMessages = [];
        const unsubscribe = wsManager.subscribe('*', (messageData, rawMessage) => {
            if (rawMessage.data && typeof rawMessage.data === 'string') {
                deepThinkMessages.push({
                    data: rawMessage.data,
                    timestamp: Date.now(),
                    type: rawMessage.type
                });
                console.log('📨 收到消息:', rawMessage.data);
            }
        });
        
        // 连接并发送深度思考消息
        await wsManager.connect();
        
        const deepThinkMessage = '请深度分析AI的发展前景';
        const deepThinkOptions = {
            deepThink: true,
            webSearch: false
        };
        
        console.log('📤 发送深度思考消息:', deepThinkMessage);
        await wsManager.sendAIMessage(deepThinkMessage, deepThinkOptions);
        
        // 等待消息处理
        await new Promise(resolve => setTimeout(resolve, 5000));
        
        // 验证深度思考流程
        const hasSeekTag = deepThinkMessages.some(msg => msg.data === '[SEEK]');
        const hasTextTag = deepThinkMessages.some(msg => msg.data === '[TEXT]');
        const hasDoneTag = deepThinkMessages.some(msg => msg.data === '[DONE]');
        const hasThinkContent = deepThinkMessages.some(msg => 
            msg.data && typeof msg.data === 'string' && 
            !msg.data.startsWith('[') && msg.data.length > 0
        );
        
        console.log('🔍 深度思考消息分析:', {
            totalMessages: deepThinkMessages.length,
            hasSeekTag,
            hasTextTag,
            hasDoneTag,
            hasThinkContent,
            messages: deepThinkMessages.map(m => ({ data: m.data, type: m.type }))
        });
        
        // 清理
        unsubscribe();
        wsManager.disconnect();
        
        const success = hasSeekTag && hasTextTag && hasDoneTag && hasThinkContent;
        
        if (success) {
            console.log('✅ Mock模式深度思考功能测试通过');
        } else {
            console.log('❌ Mock模式深度思考功能测试失败，缺少必要的消息流程');
        }
        
        return success;
        
    } catch (error) {
        console.error('❌ Mock模式深度思考测试失败:', error);
        return false;
    }
}

/**
 * 验证Mock模式配置是否正确
 */
export function validateMockConfiguration() {
    console.log('🔧 验证Mock模式配置...');
    
    const issues = [];
    
    // 检查WebSocketManager是否可以导入
    try {
        import('./WebSocketManager.js').then(module => {
            if (!module.default) {
                issues.push('WebSocketManager默认导出不存在');
            }
        }).catch(error => {
            issues.push(`WebSocketManager导入失败: ${error.message}`);
        });
    } catch (error) {
        issues.push(`无法导入WebSocketManager: ${error.message}`);
    }
    
    if (issues.length === 0) {
        console.log('✅ Mock模式配置验证通过');
        return true;
    } else {
        console.error('❌ Mock模式配置验证失败:', issues);
        return false;
    }
}

/**
 * 测试Mock模式是否完全不建立真实连接
 */
export async function testMockNoRealConnection() {
    console.log('🚫 测试Mock模式是否建立真实连接...');
    
    // 监控网络请求
    const originalFetch = window.fetch;
    const originalWebSocket = window.WebSocket;
    
    let hasNetworkRequest = false;
    let hasWebSocketConnection = false;
    
    // 拦截fetch请求
    window.fetch = (...args) => {
        console.warn('❌ 检测到fetch请求:', args[0]);
        hasNetworkRequest = true;
        return originalFetch(...args);
    };
    
    // 拦截WebSocket连接
    window.WebSocket = function(...args) {
        console.warn('❌ 检测到WebSocket连接尝试:', args[0]);
        hasWebSocketConnection = true;
        return new originalWebSocket(...args);
    };
    
    try {
        // 测试WebSocket管理器在Mock模式下的行为
        const WebSocketManager = (await import('./WebSocketManager.js')).default;
        
        const wsManager = WebSocketManager.getInstance({
            mockMode: true,
            agentId: 'no-connection-test',
            historyId: 'no-connection-test-001',
            url: null, // 确保URL为null
            logging: { enabled: true, level: 'debug' }
        });
        
        console.log('🔗 开始Mock连接测试...');
        await wsManager.connect();
        
        console.log('📤 开始Mock消息发送测试...');
        await wsManager.sendAIMessage('测试消息，不应该有真实网络请求', {
            deepThink: true,
            webSearch: false
        });
        
        // 等待一段时间确保没有延迟的网络请求
        await new Promise(resolve => setTimeout(resolve, 2000));
        
        // 清理
        wsManager.disconnect();
        
    } finally {
        // 恢复原始函数
        window.fetch = originalFetch;
        window.WebSocket = originalWebSocket;
    }
    
    const result = !hasNetworkRequest && !hasWebSocketConnection;
    
    if (result) {
        console.log('✅ Mock模式测试通过：没有检测到任何真实网络连接');
    } else {
        console.error('❌ Mock模式测试失败：检测到真实网络连接', {
            hasNetworkRequest,
            hasWebSocketConnection
        });
    }
    
    return result;
}

/**
 * 运行完整的Mock模式测试套件
 */
export async function runMockTestSuite() {
    console.log('🚀 开始运行Mock模式测试套件...');
    
    const results = {
        configuration: false,
        connection: false,
        noRealConnection: false,
        deepThink: false,
        overall: false
    };
    
    try {
        // 1. 配置验证
        console.log('\n📋 1. 配置验证测试');
        results.configuration = validateMockConfiguration();
        
        // 2. 连接功能测试
        console.log('\n🔗 2. 连接功能测试');
        results.connection = await testMockWebSocketConnection();
        
        // 3. 真实连接检测测试
        console.log('\n🚫 3. 真实连接检测测试');
        results.noRealConnection = await testMockNoRealConnection();
        
        // 4. 深度思考测试
        console.log('\n🧠 4. 深度思考功能测试');
        results.deepThink = await testMockDeepThink();
        
        // 计算总体结果
        results.overall = results.configuration && results.connection && 
                         results.noRealConnection && results.deepThink;
        
        console.log('\n📊 测试结果汇总:', results);
        
        if (results.overall) {
            console.log('🎉 所有Mock模式测试通过！Mock模式完全正常工作！');
        } else {
            console.log('⚠️ 部分Mock模式测试失败，请检查具体问题:');
            if (!results.configuration) console.log('  ❌ 配置验证失败');
            if (!results.connection) console.log('  ❌ 连接功能测试失败');
            if (!results.noRealConnection) console.log('  ❌ 仍然检测到真实网络连接');
            if (!results.deepThink) console.log('  ❌ 深度思考功能测试失败');
        }
        
        return results;
        
    } catch (error) {
        console.error('❌ Mock模式测试套件执行失败:', error);
        return { ...results, error: error.message };
    }
}

// 如果在浏览器环境，添加到window对象供调试使用
if (typeof window !== 'undefined') {
    window.testMockMode = {
        testConnection: testMockWebSocketConnection,
        testNoRealConnection: testMockNoRealConnection,
        testDeepThink: testMockDeepThink,
        validateConfig: validateMockConfiguration,
        runSuite: runMockTestSuite
    };
    
    console.log('🛠️ Mock模式测试工具已添加到window.testMockMode');
    console.log('   - window.testMockMode.testConnection() : 测试连接功能');
    console.log('   - window.testMockMode.testNoRealConnection() : 测试是否有真实连接');
    console.log('   - window.testMockMode.testDeepThink() : 测试深度思考功能');
    console.log('   - window.testMockMode.validateConfig() : 验证配置');
    console.log('   - window.testMockMode.runSuite() : 运行完整测试套件');
} 